<script setup lang="ts" name="DeptOrPerson">
import { ref, reactive, watch, computed } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { ElTree } from 'element-plus'
import type { Tree, Persons } from '@/views/selectPerson/data'

/**
 * @param departments 部门数据
 * @param persons 人员数据
 * @isMultiple 是否多选
 */
const { departments = [], persons =[], isMultiple = true } = defineProps<{
    departments?: Tree[]
    persons?: Persons[]
    isMultiple?: boolean
  }>()


const visible = ref(false)
const setVisible = (nv: boolean) => {
  visible.value = nv
}

const searchForm = reactive({
  username: '',
  phone: '',
})

const handleSearch = () => {
  console.log('submit!')
}

// dept tree

const filterDeptText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()

watch(filterDeptText, val => {
  treeRef.value!.filter(val)
})

const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}

// 当前选中部门key组
const checkedDeptKeys = ref<(string | number)[]>([])

interface Node {
  checkedNodes: Tree[]
  checkedKeys: (string | number)[]
  halfCheckedNodes: Tree[]
  halfCheckedKeys: (string | number)[]
}

const handleCheck = (e: Tree, node: Node) => {
  checkedDeptKeys.value = node.checkedKeys
}

// check all
// 当前可操作人员组
const currentPersonsData = computed(() => {
  if (departments.length) {
    return persons.filter(person =>
      checkedDeptKeys.value.includes(person.deptId),
    )
  } else {
    return persons
  }
})

// 当前选中人员组
const checkedPersonsKey = ref<string[]>([])

const checkAll = (flag: boolean) => {
  const arr = currentPersonsData.value.map(c => c.value)
  checkedPersonsKey.value = flag ? arr : []
}

// 已选择人员
const checkedPersonsNode = computed(() => {
  return currentPersonsData.value.filter(person =>
    checkedPersonsKey.value.includes(person.value),
  )
})

const handleCheckChange = (val: string[]) => {
  if (!isMultiple) {
    if (checkedPersonsKey.value.length > 1) {
      checkedPersonsKey.value.shift()
    }
  } else {
    checkedPersonsKey.value = []
    currentPersonsData.value.forEach(person => {
      if (val.includes(person.value)) {
        checkedPersonsKey.value.push(person.value)
      }
    })

    console.log(checkedPersonsKey.value, 'checkedPersonsKey.value')
  }
}

// 全部清空选择人员
const clearSelectedAll = () => {
  checkedPersonsKey.value = []
}

// 确认
const handleConfirm = () => {
  emit('confirm', {
    checkedPersonsKey,
    checkedPersonsNode,
  })
  setVisible(false)
}

const emit = defineEmits(['confirm'])

defineExpose({
  checkedPersonsKey,
  checkedPersonsNode,
})
</script>
<template>
  <slot :setVisible="setVisible">
    <el-button type="primary" @click="visible = true">Primary</el-button>
  </slot>
  <el-dialog v-model="visible" title="人员选择" width="1000px">
    <div>
      <!-- search -->
      <el-form :inline="true" :model="searchForm" class="search-form-inline">
        <el-form-item label="用户姓名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号码"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button
            :icon="Refresh"
            @click="
              () => {
                searchForm = Object.assign(searchForm, {
                  username: '',
                  phone: '',
                })
              }
            "
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <!-- content -->
      <div class="content-box">
        <!-- dept tree -->
        <el-card
          v-if="departments.length"
          class="content-card"
          body-style="padding: 5px"
          header="组织架构"
        >
          <el-input v-model="filterDeptText" placeholder="请输入部门名称" />

          <el-tree
            ref="treeRef"
            show-checkbox
            node-key="id"
            :data="departments"
            :filter-node-method="filterNode"
            class="content-item"
            @check="handleCheck"
          />
        </el-card>
        <!-- person -->
        <el-card class="content-card">
          <template #header>
            <div class="card-header">
              <span>人员选择</span>
              <div v-if="!!isMultiple">
                <span class="select" @click="checkAll(true)"> 全选 </span>
                <span class="select" @click="checkAll(false)"> 全不选 </span>
              </div>
            </div>
          </template>
          <el-checkbox-group
            class="content-item"
            v-model="checkedPersonsKey"
            @change="handleCheckChange"
          >
            <div
              class="person-item"
              v-for="person in currentPersonsData"
              :key="person.value"
            >
              <el-checkbox :label="person.label" :value="person.value">
                {{ person.label }}--({{ person.deptName }})
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </el-card>
        <!-- selected-person -->
        <el-card class="content-card">
          <template #header>
            <div class="card-header">
              <span>已选择人员</span>
              <span class="select" @click="clearSelectedAll"> 全部清空 </span>
            </div>
          </template>
          <div class="selected-person">
            <span v-for="person in checkedPersonsNode" :key="person.value">
              {{ person.label }}-<i>{{ person.deptName }}</i>
            </span>
          </div>
        </el-card>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="setVisible(false)">取消</el-button>
        <el-button type="primary" @click="handleConfirm"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.search-form-inline .el-input {
  --el-input-width: 220px;
}

// content box
.content-box {
  display: flex;

  .content-card {
    flex: 1;
    margin-right: 10px;

    &:last-child {
      margin-right: 0;
    }

    .content-item {
      height: 400px;
      overflow-y: auto;
    }
  }
}

::v-deep(.el-card__header) {
  background-color: #f5f5f5;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .select {
      padding: 0 8px;
      color: #eb6100;
      cursor: pointer;
    }
  }
}

// checkbox
.person-item {
  display: flex;
  width: 100%;
}

// selected-person
.selected-person {
  display: flex;
  width: 100%;
  flex-wrap: wrap;
  span {
    display: block;
    height: 20px;
    margin: 10px;
    i {
      font-size: 12px;
    }
  }
}
</style>
